package sisi.corporation;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.Sessions;
import org.zkoss.zk.ui.SuspendNotAllowedException;
import org.zkoss.zk.ui.event.CreateEvent;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.ForwardEvent;
import org.zkoss.zk.ui.sys.ComponentsCtrl;
import org.zkoss.zk.ui.util.ConventionWires;
import org.zkoss.zul.Intbox;
import org.zkoss.zul.ListModelList;
import org.zkoss.zul.Listbox;
import org.zkoss.zul.Listcell;
import org.zkoss.zul.Listitem;
import org.zkoss.zul.ListitemRenderer;
import org.zkoss.zul.Messagebox;
import org.zkoss.zul.Textbox;
import org.zkoss.zul.Toolbarbutton;
import org.zkoss.zul.Window;

import sisi.General;
import sisi.ListaStandardWindow;


/**
 * CorporationsWindow.java - Controller class for <i>Corporations window</i>. 
 * @author Pedro Gonzalez pedro@sisisoftware.it
 * @author Claudio Pelosi claudio@sisisoftware.it
 * @author SISI Software S.n.c. - www.sisisoftware.it
 * @version 1.0, 04/11/2013
 * 
 */

@SuppressWarnings({ "rawtypes", "unchecked", "serial" })
public class CorporationsWindow extends Window implements
		org.zkoss.zk.ui.ext.AfterCompose, ListaStandardWindow {
	
	// listbox boxCorporations
	private Window windowCorporations, windowEditCorporation;
	private Textbox tbCerca;
	private Listbox boxCorporations;

	private List tutte_le_corporations;
	private boolean lNuovo;
	private Toolbarbutton buttonSeleziona;

	private ListModelList listModelList;
	private Integer idSelezionato = 0;

	protected Map<String, Object> args;
	private Object corporationItem;
	private Corporation modCorporation;
	// edit
	private Intbox id;
	private Textbox name, contactname, contacttitle, address, city, region, postalcode, country, phone, fax, gsm, email;

	public void onCreate$windowCorporations(Event event) {

		CreateEvent ce = (CreateEvent) ((ForwardEvent) event).getOrigin();
		args = (Map<String, Object>) ce.getArg();
		String tastoSeleziona = (String) args.get("tastoSeleziona");
		tastoSeleziona = (tastoSeleziona == null || tastoSeleziona.isEmpty() ? "N"
				: tastoSeleziona);
		boolean lTastoSeleziona = tastoSeleziona.equals("S");
		if (!lTastoSeleziona) {
			buttonSeleziona.setVisible(false);
		}
		idSelezionato = (Integer) args.get("idselezionato");

		listModelList = new ListModelList();
		tutte_le_corporations = new CorporationController().getCorporationList(null);
		listModelList.addAll(tutte_le_corporations);
		boxCorporations.setModel(listModelList);
		boxCorporations.setItemRenderer(new CorporationsItemRenderer());
		
		if (idSelezionato!=null && idSelezionato!=0){
			for (int i = 0; i < tutte_le_corporations.size(); i++) {
				Corporation corp = (Corporation)tutte_le_corporations.get(i);
				if (corp.getCorpid()==idSelezionato.intValue()){
					boxCorporations.setSelectedIndex(i);
					break;
				}
			}
		}

	}

	public void afterCompose() {

		// wire variables
		ConventionWires.wireVariables(this, this);

		// auto forward
		ConventionWires.addForwards(this, this);

	}

	public void onOK$tbCerca(Event event){
		cerca();
	}
	
	public void onClick$buttonCerca(Event event) {
		cerca();
	}
	
	
	private void cerca(){
		listModelList = new ListModelList();
		tutte_le_corporations = new CorporationController().getCorporationList(tbCerca
				.getValue());
		listModelList.addAll(tutte_le_corporations);
		boxCorporations.setModel(listModelList);
		boxCorporations.setItemRenderer(new CorporationsItemRenderer());		
	}
	
	
	
	public void onDoubleClicked(Event event) {
		if (buttonSeleziona.isVisible()) {
			selezionaCorp();
		} else {
			modifica(false);
		}
	}
	
	
	public void onClick$buttonSeleziona(Event event) {

		selezionaCorp();

	}

	public void selezionaCorp() {
		if (boxCorporations.getSelectedIndex() >= 0 && buttonSeleziona.isVisible()) {
			Object oCorporation = boxCorporations.getSelectedItem().getAttribute(
					"rigaCorporation");
			String codiceSelezionato = ""+((Corporation) oCorporation).getCorpid();
			Sessions.getCurrent().setAttribute("codiceCorporationSelezionato",
					codiceSelezionato);
			windowCorporations.detach();
		}
	}


	@Override
	public void onClick$buttonNuovo(Event event) {
		modifica(true);
	}

	@Override
	public void onClick$buttonModifica(Event event) {
		modifica(false);
	}
	
	private void modifica(boolean nuovo){
		try {

			int nIndex = boxCorporations.getSelectedIndex();

			if (!nuovo && nIndex == -1) { // nessuna riga selezionata

				Messagebox.show("Select a Corporation to modify", "Information", Messagebox.OK, Messagebox.INFORMATION);

			} else {
				HashMap map = new HashMap();
				if (nuovo){
					map.put("lNuovo", true);
				}
				map.put("boxCorporations", boxCorporations);
				Window finestraEditCorporation = (Window) Executions.createComponents(
						"/editCorporation.zul", null, map);
				finestraEditCorporation.doModal();
			}

		} catch (SuspendNotAllowedException e) {
			e.printStackTrace();
		}
	}
	
	
	
	@Override
	public void onClick$buttonCancella(Event event) {
		// TODO Auto-generated method stub
		
	}	

	public class CorporationsItemRenderer implements ListitemRenderer {

		public void render(Listitem li, Object data, int index) {
			new Listcell(""+((Corporation) data).getCorpid()).setParent(li);
			new Listcell(((Corporation) data).getCorpname()).setParent(li);
			li.setAttribute("rigaCorporation", data);
			ComponentsCtrl.applyForward(li, "onDoubleClick=onDoubleClicked");
		}
	}

	
	
	// EDIT CORPORATION: NEW/MODIFY
	public void onCreate$windowEditCorporation(Event event) {

		CreateEvent ce = (CreateEvent) ((ForwardEvent) event).getOrigin();
		args = (Map<String, Object>) ce.getArg();
		
		boxCorporations = (Listbox) args.get("boxCorporations");

		if (args.containsKey("lNuovo")) {
			lNuovo = true;
		} else {
			lNuovo = false;
		}

		if (!lNuovo) {
			corporationItem = boxCorporations.getSelectedItem().getAttribute("rigaCorporation");
			modCorporation = new CorporationController()
					.refreshCorporation((Corporation) corporationItem);
			corporationItem = modCorporation;
			windowEditCorporation.setTitle("Edit Corporation");
			name.setFocus(true);
			id.setValue(modCorporation.getCorpid());
			name.setValue(modCorporation.getCorpname());
			contactname.setValue(modCorporation.getContactname());
			contacttitle.setValue(modCorporation.getContacttitle());
			address.setValue(modCorporation.getAddress());
			city.setValue(modCorporation.getCity());
			region.setValue(modCorporation.getRegion());
			postalcode.setValue(modCorporation.getPostalcode());
			country.setValue(modCorporation.getCountry());
			phone.setValue(modCorporation.getPhone());
			fax.setValue(modCorporation.getFax());
			gsm.setValue(modCorporation.getGsm());
			email.setValue(modCorporation.getEmail());
		} else {
			windowEditCorporation.setTitle("New Corporation");
			name.setFocus(true);
		}

	}
	
	public void onClick$btnAnnulla(Event event){
		windowEditCorporation.detach();
	}
	
	public void onClick$btnConferma(Event event){
		if (lNuovo){
			modCorporation = new Corporation();
		} else {

		}
		String testoMsg = "";
		
		modCorporation.setAddress(General.toUpperAncheNull(address.getValue()));
		modCorporation.setCity(General.toUpperAncheNull(city.getValue()));
		modCorporation.setContactname(General.toUpperAncheNull(contactname.getValue()));
		modCorporation.setContacttitle(General.toUpperAncheNull(contacttitle.getValue()));
		modCorporation.setCorpid(id.getValue());
		modCorporation.setCorpname(General.toUpperAncheNull(name.getValue()));
		modCorporation.setCountry(General.toUpperAncheNull(country.getValue()));
		modCorporation.setEmail(email.getValue());
		modCorporation.setFax(fax.getValue());
		modCorporation.setGsm(gsm.getValue());
		modCorporation.setPhone(phone.getValue());
		modCorporation.setPostalcode(postalcode.getValue());
		modCorporation.setRegion(General.toUpperAncheNull(region.getValue()));
		
		if (lNuovo){
			new CorporationController().addCorporation(modCorporation);
			testoMsg = "Adding Corporation: "+ General.trimNull( modCorporation.getCorpname() );
		} else {
			new CorporationController().updateCorporation(modCorporation);
			testoMsg = "Updating Corporation: "+ General.trimNull( modCorporation.getCorpname() );			
		}
		
		General.showNotify( testoMsg, windowEditCorporation);		
		
		windowEditCorporation.detach();
		
		// aggiorna listbox
		
		if (lNuovo){
			ListModelList lml = (ListModelList) boxCorporations.getListModel();
			lml.add(modCorporation);
			boxCorporations.setSelectedIndex(lml.indexOf(modCorporation));
		} else {
			ListModelList lml = (ListModelList) boxCorporations.getListModel();
			Object oCorporationItem = boxCorporations.getSelectedItem().getAttribute("rigaCorporation");
			if (lml.indexOf(oCorporationItem) == -1) {
				// non trovato... quindi non lo aggiorno
			} else {
				lml.set(lml.indexOf(oCorporationItem), modCorporation);
			}
		}		
	}
	
	
}
